Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [60]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = "train.p"
validation_file= "valid.p"
testing_file = "test.p"

with open(training_file, mode='rb') as f:
    train = pickle.load(f)

with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
    
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
#Save date set to disaply unaltered form later
X_train_orig, y_train_orig = train['features'], train['labels']

X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [58]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

# TODO: Number of training examples
n_train = y_train.size

# TODO: Number of testing examples.
n_test = y_test.size

# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape

# TODO: How many unique classes/labels there are in the dataset.
set_of_labels = set(y_train)
n_classes = len(set_of_labels)

print("Number of training examples =", n_train)
print("Number of validation examples =", y_valid.size)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
print("Shape of Y=",y_train.shape)
Number of training examples = 34799
Number of validation examples = 4410
Number of testing examples = 12630
Image data shape = (32, 32, 1)
Number of classes = 43
Shape of Y= (34799,)

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [3]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import csv
import random
# Visualizations will be shown in the notebook.
%matplotlib inline

with open('signnames.csv', mode='r') as infile:
    reader = csv.reader(infile)
    sign_names = {rows[0]:rows[1] for rows in reader}

sign_names.keys()

images_to_show=50

for x in range(images_to_show):
    rand_image_num=random.randint(0,n_train)
    img = X_train[rand_image_num]

    image_name_label=sign_names[str(y_train[rand_image_num])]
    print ("Sign Type")
    print (image_name_label)
    imgplot = plt.imshow(img)
    plt.show()
    
    
Sign Type
Turn right ahead
Sign Type
No entry
Sign Type
Speed limit (30km/h)
Sign Type
Keep right
Sign Type
Children crossing
Sign Type
Turn right ahead
Sign Type
Speed limit (30km/h)
Sign Type
General caution
Sign Type
Go straight or right
Sign Type
Right-of-way at the next intersection
Sign Type
No entry
Sign Type
Speed limit (30km/h)
Sign Type
Speed limit (50km/h)
Sign Type
General caution
Sign Type
Speed limit (80km/h)
Sign Type
Yield
Sign Type
Speed limit (50km/h)
Sign Type
Turn right ahead
Sign Type
Stop
Sign Type
Priority road
Sign Type
Speed limit (80km/h)
Sign Type
Keep right
Sign Type
No passing for vehicles over 3.5 metric tons
Sign Type
Speed limit (120km/h)
Sign Type
Speed limit (120km/h)
Sign Type
Slippery road
Sign Type
No passing for vehicles over 3.5 metric tons
Sign Type
Priority road
Sign Type
Speed limit (50km/h)
Sign Type
Speed limit (120km/h)
Sign Type
Speed limit (120km/h)
Sign Type
Ahead only
Sign Type
Keep right
Sign Type
Children crossing
Sign Type
Speed limit (30km/h)
Sign Type
Speed limit (70km/h)
Sign Type
No passing
Sign Type
Speed limit (30km/h)
Sign Type
End of speed limit (80km/h)
Sign Type
Right-of-way at the next intersection
Sign Type
No entry
Sign Type
Go straight or right
Sign Type
Right-of-way at the next intersection
Sign Type
No passing for vehicles over 3.5 metric tons
Sign Type
Speed limit (100km/h)
Sign Type
Traffic signals
Sign Type
Priority road
Sign Type
Road work
Sign Type
Right-of-way at the next intersection
Sign Type
Speed limit (60km/h)
In [4]:
#Generate information on balanced data sets
hist_train_y=[]
hist_train_x=[]
y_train_list = y_train.tolist()
for x in range(0,n_classes):
    hist_train_x.append(x)
    count = y_train_list.count(x)
    hist_train_y.append(count)
    #print (sign_names[str(x)])
    #print (count)

plt.plot(hist_train_x, hist_train_y, 'ro')
plt.show()

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [61]:
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.
from sklearn.utils import shuffle
import math
import cv2
import numpy as np


def normalize_image(img):
    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    img = cv2.normalize(img.astype('float32'), None, 0.0, 1.0, cv2.NORM_MINMAX)
    img = img.reshape(img.shape[0],img.shape[1],1)
    return(img)

#Map to grascale for each image.
#for img in X_train:
#    im = color.rgb2gray(im)
X_train_gray=[]
for img in X_train:
    X_train_gray.append(normalize_image(img))
X_train=np.array(X_train_gray)


X_valid_gray=[]
for img in X_valid:
    X_valid_gray.append( normalize_image(img))
X_valid=np.array(X_valid_gray)


X_test_gray=[]
for img in X_test:
    X_test_gray.append(normalize_image(img))
X_test=np.array(X_test_gray)



image_shape = X_train[0].shape
print (image_shape)
(32, 32, 1)
In [6]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.


images_to_show=5

for x_iter in range(images_to_show):
    rand_image_num=random.randint(0,n_train)
    img = X_train[rand_image_num]
    image_name_label=sign_names[str(y_train[rand_image_num])]
    print ("Sign Type")
    print (image_name_label)
    
    img = X_train[rand_image_num]
    print(img.shape)
    img = img.reshape(img.shape[0],img.shape[1])
    imgplot = plt.imshow(img,cmap="gray")
    plt.show()
    
    plt.hist(img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
    plt.show()

    
    
    
Sign Type
Children crossing
(32, 32, 1)
Sign Type
Yield
(32, 32, 1)
Sign Type
Speed limit (60km/h)
(32, 32, 1)
Sign Type
Speed limit (120km/h)
(32, 32, 1)
Sign Type
Beware of ice/snow
(32, 32, 1)
In [7]:
#Shuffle the data

from sklearn.utils import shuffle

X_train, y_train = shuffle(X_train, y_train)

Setup Tensorflow

In [8]:
import tensorflow as tf
In [9]:
#setup TF GPU memory options
config = tf.ConfigProto()
config.gpu_options.allow_growth = True

Model Architecture

In [10]:
### Define your architecture here.
### Feel free to use as many code cells as needed.
from tensorflow.contrib.layers import flatten

def TrafficLeNet(x):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
    
    # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros(6))
    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID',name='conv1') + conv1_b

    # SOLUTION: Activation.
    conv1 = tf.nn.relu(conv1)

    # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(16))
    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID',name='conv2') + conv2_b
    
    # SOLUTION: Activation.
    conv2 = tf.nn.relu(conv2)

    # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # SOLUTION: Flatten. Input = 5x5x16. Output = 400.
    fc0   = flatten(conv2)
    
    # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(120))
    fc1   = tf.matmul(fc0, fc1_W) + fc1_b
    
    # SOLUTION: Activation.
    fc1    = tf.nn.relu(fc1)

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
    fc2_b  = tf.Variable(tf.zeros(84))
    fc2    = tf.matmul(fc1, fc2_W) + fc2_b
    
    # SOLUTION: Activation.
    fc2    = tf.nn.relu(fc2)

    # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = n_classes.
    fc3_W  = tf.Variable(tf.truncated_normal(shape=(84, n_classes), mean = mu, stddev = sigma))
    fc3_b  = tf.Variable(tf.zeros(n_classes))
    logits = tf.matmul(fc2, fc3_W) + fc3_b
    
    return logits

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [11]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
In [12]:
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)
In [13]:
# use for code testing.. not network validation
#EPOCHS = 10
#BATCH_SIZE = 32
#rate = 0.001
# - gererated validataion accuracy of 0.93

#EPOCHS = 5
#BATCH_SIZE = 256
#rate = 0.001

#EPOCHS = 3500
#BATCH_SIZE = 256
#rate=0.00001
# - gererated validataion accuracy of 0.88*.... jumped around.. 
# slow to go past at epoch 500/600
# 0.90 after 1200 epochs
# 0.91 after 3000 epochs

#EPOCHS = 1000
#BATCH_SIZE = 128
#rate=0.0001
# 0.920 very slow convergence

#EPOCHS = 1000
#BATCH_SIZE = 16
#rate=0.001
# result: 0.94 after 10 steps... let run.. 0.958 after 1000

#### Use this one for full test
EPOCHS = 100
BATCH_SIZE = 16
rate=0.001
# result: 0.953 ( dropped below 0.93 on occasion)

logits = TrafficLeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
In [14]:
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    print(X_data.shape)
    print(y_data.shape)
    
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples
In [15]:
with tf.Session() as sess:
    #setup TF GPU memory options
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)
    
    print("Training...")
    print()
    accuracy_history=[]
    for i in range(EPOCHS):
        X_train, y_train = shuffle(X_train, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
            
        validation_accuracy = evaluate(X_valid, y_valid)
        print("EPOCH {} ...".format(i+1))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
        accuracy_history.append(validation_accuracy)
        
        
    saver.save(sess, './trafficlenet')
    print("Model saved")
    
    conv_layer_2_visual = sess.graph.get_tensor_by_name('conv1:0')
    
    plt.plot( accuracy_history, 'ro')
    plt.show()
Training...

(4410, 32, 32, 1)
(4410,)
EPOCH 1 ...
Validation Accuracy = 0.904

(4410, 32, 32, 1)
(4410,)
EPOCH 2 ...
Validation Accuracy = 0.918

(4410, 32, 32, 1)
(4410,)
EPOCH 3 ...
Validation Accuracy = 0.906

(4410, 32, 32, 1)
(4410,)
EPOCH 4 ...
Validation Accuracy = 0.944

(4410, 32, 32, 1)
(4410,)
EPOCH 5 ...
Validation Accuracy = 0.948

(4410, 32, 32, 1)
(4410,)
EPOCH 6 ...
Validation Accuracy = 0.949

(4410, 32, 32, 1)
(4410,)
EPOCH 7 ...
Validation Accuracy = 0.948

(4410, 32, 32, 1)
(4410,)
EPOCH 8 ...
Validation Accuracy = 0.952

(4410, 32, 32, 1)
(4410,)
EPOCH 9 ...
Validation Accuracy = 0.950

(4410, 32, 32, 1)
(4410,)
EPOCH 10 ...
Validation Accuracy = 0.959

(4410, 32, 32, 1)
(4410,)
EPOCH 11 ...
Validation Accuracy = 0.944

(4410, 32, 32, 1)
(4410,)
EPOCH 12 ...
Validation Accuracy = 0.948

(4410, 32, 32, 1)
(4410,)
EPOCH 13 ...
Validation Accuracy = 0.944

(4410, 32, 32, 1)
(4410,)
EPOCH 14 ...
Validation Accuracy = 0.952

(4410, 32, 32, 1)
(4410,)
EPOCH 15 ...
Validation Accuracy = 0.953

(4410, 32, 32, 1)
(4410,)
EPOCH 16 ...
Validation Accuracy = 0.957

(4410, 32, 32, 1)
(4410,)
EPOCH 17 ...
Validation Accuracy = 0.940

(4410, 32, 32, 1)
(4410,)
EPOCH 18 ...
Validation Accuracy = 0.949

(4410, 32, 32, 1)
(4410,)
EPOCH 19 ...
Validation Accuracy = 0.947

(4410, 32, 32, 1)
(4410,)
EPOCH 20 ...
Validation Accuracy = 0.935

(4410, 32, 32, 1)
(4410,)
EPOCH 21 ...
Validation Accuracy = 0.943

(4410, 32, 32, 1)
(4410,)
EPOCH 22 ...
Validation Accuracy = 0.940

(4410, 32, 32, 1)
(4410,)
EPOCH 23 ...
Validation Accuracy = 0.960

(4410, 32, 32, 1)
(4410,)
EPOCH 24 ...
Validation Accuracy = 0.952

(4410, 32, 32, 1)
(4410,)
EPOCH 25 ...
Validation Accuracy = 0.953

(4410, 32, 32, 1)
(4410,)
EPOCH 26 ...
Validation Accuracy = 0.955

(4410, 32, 32, 1)
(4410,)
EPOCH 27 ...
Validation Accuracy = 0.954

(4410, 32, 32, 1)
(4410,)
EPOCH 28 ...
Validation Accuracy = 0.941

(4410, 32, 32, 1)
(4410,)
EPOCH 29 ...
Validation Accuracy = 0.957

(4410, 32, 32, 1)
(4410,)
EPOCH 30 ...
Validation Accuracy = 0.951

(4410, 32, 32, 1)
(4410,)
EPOCH 31 ...
Validation Accuracy = 0.943

(4410, 32, 32, 1)
(4410,)
EPOCH 32 ...
Validation Accuracy = 0.958

(4410, 32, 32, 1)
(4410,)
EPOCH 33 ...
Validation Accuracy = 0.961

(4410, 32, 32, 1)
(4410,)
EPOCH 34 ...
Validation Accuracy = 0.947

(4410, 32, 32, 1)
(4410,)
EPOCH 35 ...
Validation Accuracy = 0.959

(4410, 32, 32, 1)
(4410,)
EPOCH 36 ...
Validation Accuracy = 0.941

(4410, 32, 32, 1)
(4410,)
EPOCH 37 ...
Validation Accuracy = 0.951

(4410, 32, 32, 1)
(4410,)
EPOCH 38 ...
Validation Accuracy = 0.955

(4410, 32, 32, 1)
(4410,)
EPOCH 39 ...
Validation Accuracy = 0.953

(4410, 32, 32, 1)
(4410,)
EPOCH 40 ...
Validation Accuracy = 0.952

(4410, 32, 32, 1)
(4410,)
EPOCH 41 ...
Validation Accuracy = 0.952

(4410, 32, 32, 1)
(4410,)
EPOCH 42 ...
Validation Accuracy = 0.955

(4410, 32, 32, 1)
(4410,)
EPOCH 43 ...
Validation Accuracy = 0.959

(4410, 32, 32, 1)
(4410,)
EPOCH 44 ...
Validation Accuracy = 0.943

(4410, 32, 32, 1)
(4410,)
EPOCH 45 ...
Validation Accuracy = 0.955

(4410, 32, 32, 1)
(4410,)
EPOCH 46 ...
Validation Accuracy = 0.950

(4410, 32, 32, 1)
(4410,)
EPOCH 47 ...
Validation Accuracy = 0.952

(4410, 32, 32, 1)
(4410,)
EPOCH 48 ...
Validation Accuracy = 0.959

(4410, 32, 32, 1)
(4410,)
EPOCH 49 ...
Validation Accuracy = 0.947

(4410, 32, 32, 1)
(4410,)
EPOCH 50 ...
Validation Accuracy = 0.956

(4410, 32, 32, 1)
(4410,)
EPOCH 51 ...
Validation Accuracy = 0.957

(4410, 32, 32, 1)
(4410,)
EPOCH 52 ...
Validation Accuracy = 0.952

(4410, 32, 32, 1)
(4410,)
EPOCH 53 ...
Validation Accuracy = 0.946

(4410, 32, 32, 1)
(4410,)
EPOCH 54 ...
Validation Accuracy = 0.951

(4410, 32, 32, 1)
(4410,)
EPOCH 55 ...
Validation Accuracy = 0.953

(4410, 32, 32, 1)
(4410,)
EPOCH 56 ...
Validation Accuracy = 0.958

(4410, 32, 32, 1)
(4410,)
EPOCH 57 ...
Validation Accuracy = 0.953

(4410, 32, 32, 1)
(4410,)
EPOCH 58 ...
Validation Accuracy = 0.959

(4410, 32, 32, 1)
(4410,)
EPOCH 59 ...
Validation Accuracy = 0.967

(4410, 32, 32, 1)
(4410,)
EPOCH 60 ...
Validation Accuracy = 0.957

(4410, 32, 32, 1)
(4410,)
EPOCH 61 ...
Validation Accuracy = 0.957

(4410, 32, 32, 1)
(4410,)
EPOCH 62 ...
Validation Accuracy = 0.941

(4410, 32, 32, 1)
(4410,)
EPOCH 63 ...
Validation Accuracy = 0.957

(4410, 32, 32, 1)
(4410,)
EPOCH 64 ...
Validation Accuracy = 0.955

(4410, 32, 32, 1)
(4410,)
EPOCH 65 ...
Validation Accuracy = 0.958

(4410, 32, 32, 1)
(4410,)
EPOCH 66 ...
Validation Accuracy = 0.961

(4410, 32, 32, 1)
(4410,)
EPOCH 67 ...
Validation Accuracy = 0.960

(4410, 32, 32, 1)
(4410,)
EPOCH 68 ...
Validation Accuracy = 0.958

(4410, 32, 32, 1)
(4410,)
EPOCH 69 ...
Validation Accuracy = 0.959

(4410, 32, 32, 1)
(4410,)
EPOCH 70 ...
Validation Accuracy = 0.963

(4410, 32, 32, 1)
(4410,)
EPOCH 71 ...
Validation Accuracy = 0.970

(4410, 32, 32, 1)
(4410,)
EPOCH 72 ...
Validation Accuracy = 0.954

(4410, 32, 32, 1)
(4410,)
EPOCH 73 ...
Validation Accuracy = 0.952

(4410, 32, 32, 1)
(4410,)
EPOCH 74 ...
Validation Accuracy = 0.959

(4410, 32, 32, 1)
(4410,)
EPOCH 75 ...
Validation Accuracy = 0.947

(4410, 32, 32, 1)
(4410,)
EPOCH 76 ...
Validation Accuracy = 0.942

(4410, 32, 32, 1)
(4410,)
EPOCH 77 ...
Validation Accuracy = 0.945

(4410, 32, 32, 1)
(4410,)
EPOCH 78 ...
Validation Accuracy = 0.953

(4410, 32, 32, 1)
(4410,)
EPOCH 79 ...
Validation Accuracy = 0.956

(4410, 32, 32, 1)
(4410,)
EPOCH 80 ...
Validation Accuracy = 0.965

(4410, 32, 32, 1)
(4410,)
EPOCH 81 ...
Validation Accuracy = 0.956

(4410, 32, 32, 1)
(4410,)
EPOCH 82 ...
Validation Accuracy = 0.962

(4410, 32, 32, 1)
(4410,)
EPOCH 83 ...
Validation Accuracy = 0.973

(4410, 32, 32, 1)
(4410,)
EPOCH 84 ...
Validation Accuracy = 0.970

(4410, 32, 32, 1)
(4410,)
EPOCH 85 ...
Validation Accuracy = 0.954

(4410, 32, 32, 1)
(4410,)
EPOCH 86 ...
Validation Accuracy = 0.945

(4410, 32, 32, 1)
(4410,)
EPOCH 87 ...
Validation Accuracy = 0.960

(4410, 32, 32, 1)
(4410,)
EPOCH 88 ...
Validation Accuracy = 0.960

(4410, 32, 32, 1)
(4410,)
EPOCH 89 ...
Validation Accuracy = 0.946

(4410, 32, 32, 1)
(4410,)
EPOCH 90 ...
Validation Accuracy = 0.948

(4410, 32, 32, 1)
(4410,)
EPOCH 91 ...
Validation Accuracy = 0.960

(4410, 32, 32, 1)
(4410,)
EPOCH 92 ...
Validation Accuracy = 0.950

(4410, 32, 32, 1)
(4410,)
EPOCH 93 ...
Validation Accuracy = 0.961

(4410, 32, 32, 1)
(4410,)
EPOCH 94 ...
Validation Accuracy = 0.966

(4410, 32, 32, 1)
(4410,)
EPOCH 95 ...
Validation Accuracy = 0.965

(4410, 32, 32, 1)
(4410,)
EPOCH 96 ...
Validation Accuracy = 0.969

(4410, 32, 32, 1)
(4410,)
EPOCH 97 ...
Validation Accuracy = 0.970

(4410, 32, 32, 1)
(4410,)
EPOCH 98 ...
Validation Accuracy = 0.966

(4410, 32, 32, 1)
(4410,)
EPOCH 99 ...
Validation Accuracy = 0.960

(4410, 32, 32, 1)
(4410,)
EPOCH 100 ...
Validation Accuracy = 0.951

Model saved

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [48]:
#Images loaded from http://finde-das-bild.de/bildersuche?keys=verkehrsschild based on comments in slack channle.

import PIL
from PIL import Image

web_filedir="german-web-test-images/"
#german_images=["achtung-ampel.jpg","doppelkurve.jpg","geradeaus.jpg",
#               "hoechstgeschw_70.jpg","rechts_vorbei.jpg","vorfahrtsstrasse.jpg"]

#y_german_test=[26,21,35,4,38,12]

web_test_images=["30speed.jpg","Caution.jpg","Do-Not-Enter.jpg",
                 "PriorityRoad.jpg",
                 "roadWorks-2.jpg","stop.jpg"]


y_webtest_test=[1,18,17,12,25,14]

def process_images(images,y_test):
    x_int=0
    X_test=[]
    X_test_img=[]
    for image_name in images:
        print(web_filedir+image_name)
        print(sign_names[str(y_test[x_int])])
        x_int = x_int+1
        img = Image.open(web_filedir+image_name)
        X_test_img.append(img)
        imgplot = plt.imshow(img)
        plt.show()
        img = img.resize((32,32),Image.ANTIALIAS)
        img = np.array(img.getdata(),np.uint8).reshape(img.size[1], img.size[0], 3)
        imgplot = plt.imshow(img)
        plt.show()
        print(img.shape)
        img = normalize_image(img)
    
        img_a = img.reshape(img.shape[0],img.shape[1])
        imgplot = plt.imshow(img_a,cmap="gray")
        plt.show()
    
        plt.hist(img_a.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
        plt.show()
        print (img_a.shape)
        print (img.shape)

        plt.show()
        X_test.append(img)

    X_test=np.array(X_test)
    y_test = np.array(y_test)
    
    return(X_test,y_test)
    

X_webtest_test,y_webtest_test = process_images(web_test_images,y_webtest_test)
print(X_webtest_test.shape)
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
german-web-test-images/30speed.jpg
Speed limit (30km/h)
(32, 32, 3)
(32, 32)
(32, 32, 1)
german-web-test-images/Caution.jpg
General caution
(32, 32, 3)
(32, 32)
(32, 32, 1)
german-web-test-images/Do-Not-Enter.jpg
No entry
(32, 32, 3)
(32, 32)
(32, 32, 1)
german-web-test-images/PriorityRoad.jpg
Priority road
(32, 32, 3)
(32, 32)
(32, 32, 1)
german-web-test-images/roadWorks-2.jpg
Road work
(32, 32, 3)
(32, 32)
(32, 32, 1)
german-web-test-images/stop.jpg
Stop
(32, 32, 3)
(32, 32)
(32, 32, 1)
(6, 32, 32, 1)

Predict the Sign Type for Each Image

In [49]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.


    
#def get_prediction(img1):
#    with tf.Session() as sess:
#        # Restore vairables
#        saver.restore(sess,'./trafficlenet')
#        img1_tensor = tf.convert_to_tensor(img1)
#        img1_tensor = tf.reshape(img1_tensor, (1, 32, 32,1 ))
#        img1_tensor = tf.cast(img1_tensor, tf.float32)

#        logits = TrafficLeNet(img1_tensor)

#        logits = tf.nn.softmax(logits)
#        pred = sess.run(logits)
#        best_preds, best_indices = tf.nn.top_k(pred, k=5)
#        best_preds, best_indices  = sess.run([best_preds, best_indices])
        
#        print("Top Predictions {}".format(best_indices))
#        return pred, best_preds, best_indices

#img1 = X_german_test[0]
#print("Image 1 ")
#p1, bp1, bi1 = get_prediction(img1)
def get_prediction(img_list):
    with tf.Session() as sess:
        saver.restore(sess,'./trafficlenet')

        #correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
        #logits = tf.nn.softmax(logits)
#accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        #accuracy = sess.run( correct_prediction,feed_dict={x: img1})
        #accuracy = sess.run( logits,feed_dict={x: img1})


        get_soft_max = tf.nn.softmax(logits)
        
        #pred = sess.run(get_soft_max,feed_dict={x: img_list})
        pred = sess.run(get_soft_max,feed_dict={x: img_list})
        best_preds, best_indices = tf.nn.top_k(pred, k=5)
        best_preds, best_indices  = sess.run([best_preds, best_indices])
        print("Top Predictions {}".format(best_indices))

        
        
        return 


print(y_webtest_test)
get_prediction(X_webtest_test)


    
    
[ 1 18 17 12 25 14]
Top Predictions [[ 1 25 13 35 33]
 [18  0  1  2  3]
 [17  0  1  2  3]
 [12  0  1  2  3]
 [25 18  5  2  1]
 [14  0  1  2  3]]

Analyze Performance

In [62]:
### Calculate the accuracy for these Test  images. 

with tf.Session() as sess:
    #saver.restore(sess, tf.train.latest_checkpoint('.'))

    saver.restore(sess, './trafficlenet')
    
    test_accuracy = evaluate(X_test, y_test)
    print("Test Accuracy = {:.3f}".format(test_accuracy)) 
(12630, 32, 32, 1)
(12630,)
Web Test Accuracy = 0.941
In [50]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.

with tf.Session() as sess:
    #saver.restore(sess, tf.train.latest_checkpoint('.'))

    saver.restore(sess, './trafficlenet')
    
    test_accuracy = evaluate(X_webtest_test, y_webtest_test)
    print("Web Test Accuracy = {:.3f}".format(test_accuracy)) 
(6, 32, 32, 1)
(6,)
Web Test Accuracy = 1.000

Output Top 5 Softmax Probabilities For Each Image Found on the Web

In [51]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.
In [52]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.

    
#def get_prediction(img1):
#    with tf.Session() as sess:
#        # Restore vairables
#        saver.restore(sess,'./trafficlenet')
#        img1_tensor = tf.convert_to_tensor(img1)
#        img1_tensor = tf.reshape(img1_tensor, (1, 32, 32,1 ))
#        img1_tensor = tf.cast(img1_tensor, tf.float32)

#        logits = TrafficLeNet(img1_tensor)

#        logits = tf.nn.softmax(logits)
#        pred = sess.run(logits)
#        best_preds, best_indices = tf.nn.top_k(pred, k=5)
#        best_preds, best_indices  = sess.run([best_preds, best_indices])
        
#        print("Top Predictions {}".format(best_indices))
#        return pred, best_preds, best_indices

#img1 = X_german_test[0]
#print("Image 1 ")
#p1, bp1, bi1 = get_prediction(img1)
def get_prob_prediction(img_list):
    with tf.Session() as sess:
        saver.restore(sess,'./trafficlenet')

        #correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
        #logits = tf.nn.softmax(logits)
#accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        #accuracy = sess.run( correct_prediction,feed_dict={x: img1})
        #accuracy = sess.run( logits,feed_dict={x: img1})


        get_soft_max = tf.nn.softmax(logits)
        
        #pred = sess.run(get_soft_max,feed_dict={x: img_list})
        pred = sess.run(get_soft_max,feed_dict={x: img_list})
        best_preds, best_indices = tf.nn.top_k(pred, k=5)
        best_preds, best_indices  = sess.run([best_preds, best_indices])
        print("Top Predictions {}".format(best_indices))
        print("Top Probabilites {}".format(best_preds))
        
        
        return [best_preds, best_indices]


print(y_webtest_test)
[best_preds, best_indices] = get_prob_prediction(X_webtest_test)
#print("Top Predictions {}".format(best_indices))
#print("Top Probabilites {}".format(best_preds))

x_iter=0
for image in web_test_images:
    print ("******************************")
    print ("Image name:" + image)
    image_name_label=sign_names[str(y_webtest_test[x_iter])]
    print ("Test Sign Type:"+image_name_label)
    predicted_sign_type = best_indices[x_iter][0]
    predicted_prob=best_preds[x_iter][0]
    
    print ("Predicted sign type (highest prob):"+sign_names[str(predicted_sign_type)]+" With Prob:"+str(predicted_prob))
    
    sign_type = y_webtest_test[x_iter]
    print("There were "+ str(np.count_nonzero(y_train == sign_type)) + " samples in the training set")

    img = Image.open(web_filedir+image)
    imgplot = plt.imshow(img)
    plt.show()
    
    if predicted_sign_type == sign_type:
        print("** Correct prediction")
    else:
        print("** INCORRECT  prediction")
        print("Showing some examples of training set")
        sign_type=y_webtest_test[x_iter]
        indx_of_signs = np.nonzero(y_train_orig == sign_type)
        for randcount in range(0,5):
            rand_image_num_index=random.randint(0,len(indx_of_signs[0]))
            print (rand_image_num_index)
            rand_image_num = indx_of_signs[0][rand_image_num_index]
            print (rand_image_num)
            img = X_train_orig[rand_image_num]
            imgplot = plt.imshow(img)
            plt.show()
        print("Showing some examples of what the network predicted")
        sign_type=predicted_sign_type
        indx_of_signs = np.nonzero(y_train_orig == sign_type)
        for randcount in range(0,5):
            rand_image_num_index=random.randint(0,len(indx_of_signs[0]))
            print (rand_image_num_index)
            rand_image_num = indx_of_signs[0][rand_image_num_index]
            print (rand_image_num)
            img = X_train_orig[rand_image_num]
            imgplot = plt.imshow(img)
            plt.show()
        
    
    x_iter = x_iter+1
    
    
    
[ 1 18 17 12 25 14]
Top Predictions [[ 1 25 13 35 33]
 [18  0  1  2  3]
 [17  0  1  2  3]
 [12  0  1  2  3]
 [25 18  5  2  1]
 [14  0  1  2  3]]
Top Probabilites [[  1.00000000e+00   1.96827918e-20   6.85512281e-21   3.19096405e-32
    1.68744447e-32]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]
 [  1.00000000e+00   1.21836392e-13   2.61300410e-19   1.40272426e-24
    1.32298014e-25]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]]
Top Predictions [[ 1 25 13 35 33]
 [18  0  1  2  3]
 [17  0  1  2  3]
 [12  0  1  2  3]
 [25 18  5  2  1]
 [14  0  1  2  3]]
Top Probabilites [[  1.00000000e+00   1.96827918e-20   6.85512281e-21   3.19096405e-32
    1.68744447e-32]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]
 [  1.00000000e+00   1.21836392e-13   2.61300410e-19   1.40272426e-24
    1.32298014e-25]
 [  1.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]]
******************************
Image name:30speed.jpg
Test Sign Type:Speed limit (30km/h)
Predicted sign type (highest prob):Speed limit (30km/h) With Prob:1.0
There were 1980 samples in the training set
** Correct prediction
******************************
Image name:Caution.jpg
Test Sign Type:General caution
Predicted sign type (highest prob):General caution With Prob:1.0
There were 1080 samples in the training set
** Correct prediction
******************************
Image name:Do-Not-Enter.jpg
Test Sign Type:No entry
Predicted sign type (highest prob):No entry With Prob:1.0
There were 990 samples in the training set
** Correct prediction
******************************
Image name:PriorityRoad.jpg
Test Sign Type:Priority road
Predicted sign type (highest prob):Priority road With Prob:1.0
There were 1890 samples in the training set
** Correct prediction
******************************
Image name:roadWorks-2.jpg
Test Sign Type:Road work
Predicted sign type (highest prob):Road work With Prob:1.0
There were 1350 samples in the training set
** Correct prediction
******************************
Image name:stop.jpg
Test Sign Type:Stop
Predicted sign type (highest prob):Stop With Prob:1.0
There were 690 samples in the training set
** Correct prediction

Step 4: Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [53]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it maybe having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
    plt.show()
In [54]:
x_iter=0

with tf.Session() as sess:
    saver.restore(sess,'./trafficlenet')

    print (X_webtest_test.shape)
    print (X_webtest_test[0].shape)
    
    x_iter = 0
    
    for image in web_test_images:
        print ("******************************")
        print ("Image name:" + image)
        image_name_label=sign_names[str(y_webtest_test[x_iter])]
        print ("Test Sign Type:"+image_name_label)
        predicted_sign_type = best_indices[x_iter][0]
        predicted_prob=best_preds[x_iter][0]

        print ("Predicted sign type (highest prob):"+sign_names[str(predicted_sign_type)]+" With Prob:"+str(predicted_prob))

        sign_type = y_webtest_test[x_iter]
        print("There were "+ str(np.count_nonzero(y_train == sign_type)) + " samples in the training set")

        img = Image.open(web_filedir+image)
        imgplot = plt.imshow(img)
        plt.show()

        if predicted_sign_type == sign_type:
            print("** Correct prediction")
        else:
            print("** INCORRECT  prediction")
            
        X_test = X_webtest_test[x_iter].reshape(1, 32,32,1)
        print (X_test.shape)
        conv_layer_1_visual = sess.graph.get_tensor_by_name('conv1:0')
        outputFeatureMap(X_test,conv_layer_1_visual)
    
        conv_layer_2_visual = sess.graph.get_tensor_by_name('conv2:0')
        outputFeatureMap(X_test,conv_layer_2_visual)

        x_iter = x_iter+1


    
(6, 32, 32, 1)
(32, 32, 1)
******************************
Image name:30speed.jpg
Test Sign Type:Speed limit (30km/h)
Predicted sign type (highest prob):Speed limit (30km/h) With Prob:1.0
There were 1980 samples in the training set
** Correct prediction
(1, 32, 32, 1)
******************************
Image name:Caution.jpg
Test Sign Type:General caution
Predicted sign type (highest prob):General caution With Prob:1.0
There were 1080 samples in the training set
** Correct prediction
(1, 32, 32, 1)
******************************
Image name:Do-Not-Enter.jpg
Test Sign Type:No entry
Predicted sign type (highest prob):No entry With Prob:1.0
There were 990 samples in the training set
** Correct prediction
(1, 32, 32, 1)
******************************
Image name:PriorityRoad.jpg
Test Sign Type:Priority road
Predicted sign type (highest prob):Priority road With Prob:1.0
There were 1890 samples in the training set
** Correct prediction
(1, 32, 32, 1)
******************************
Image name:roadWorks-2.jpg
Test Sign Type:Road work
Predicted sign type (highest prob):Road work With Prob:1.0
There were 1350 samples in the training set
** Correct prediction
(1, 32, 32, 1)
******************************
Image name:stop.jpg
Test Sign Type:Stop
Predicted sign type (highest prob):Stop With Prob:1.0
There were 690 samples in the training set
** Correct prediction
(1, 32, 32, 1)

Question 9

Discuss how you used the visual output of your trained network's feature maps to show that it had learned to look for interesting characteristics in traffic sign images

Answer:

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.